package cn.crsc.openlookeng.config;

import cn.crsc.openlookeng.enums.DataSourceType;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class GlobalDataSourceConfiguration {

	@Bean(name = "openlookengDataSource")
	@ConfigurationProperties(prefix = "spring.datasource.openlookeng")
	public DataSource openlookengDataSource() {

		DataSource dataSource = DataSourceBuilder.create().build();
		return dataSource;
	}


	/*
	 * 动态数据源
	 * dbMap中存放数据源名称与数据源实例，数据源名称存于DataEnum.DbSource中
	 * setDefaultTargetDataSource方法设置默认数据源
	 */

	@Bean(name = "dynamicDataSource")
	@Primary
	public DynamicDataSourceRouting dataSource(DataSource openlookengDataSource)
	{
		Map<Object, Object> targetDataSources = new HashMap<>();
		targetDataSources.put(DataSourceType.openlookeng.name(), openlookengDataSource);
		return new DynamicDataSourceRouting(openlookengDataSource, targetDataSources);
	}


	@Bean
	public DataSourceTransactionManager openLookengTransactionManager(@Qualifier("dynamicDataSource") DataSource dataSource){

		return new DataSourceTransactionManager(dataSource);
	}


}